package fun.wlfj.servlet;

import java.io.IOException;
import java.util.LinkedList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import fun.wlfj.vo.VoteTask;

/**
 * Servlet implementation class submitservlet
 */
@WebServlet("/submitservlet")
public class submitservlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public submitservlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		// 现在数据到来了 我们要得到其中的投票id 和 当前的选择 将其添加到记录队列中.
		// 在数据到来时候 我们要将其与队列最上面进行比较 之后将内容更新
		String message = null;
		int VoteID = -1, Choose = 1;
		try {
			VoteID = Integer.parseInt(request.getParameter("VoteID"));
			Choose = Integer.parseInt(request.getParameter("Choose"));
		}catch(NumberFormatException e) {
			message = "您未表态或非法请求.<br>点击下方按钮重新投票.";
			request.setAttribute("message", message);
			request.getRequestDispatcher("finished.jsp").forward(request, response);
			response.getWriter().append("Served at: ").append(request.getContextPath());
			return;
		}
		// 首先判断当前ID是否合法
		@SuppressWarnings("unchecked")
		LinkedList<VoteTask> taskList = (LinkedList<VoteTask>)this.getServletContext().getAttribute("TaskList");
		VoteTask task = taskList.getLast();
		
		if(task.getVoteID() == VoteID && !task.isFinished()) {
			// 我们将数据记录 同时更新投票信息
			int currentVoteID = -1;
			Object t = null;
			if((t = request.getSession().getAttribute("CurrentVoteID")) != null) {
				currentVoteID = (Integer)t;
			}
			if(currentVoteID != VoteID) {
				synchronized (task) {
					task.add(Choose);
				}
				// 更新投票数据
				request.getSession().setAttribute("CurrentVoteID", VoteID);
				message = "投票成功!";
			}else {
				message = "请勿重复投票!";
			}
			// 更新投票信息
		}else {
			// ID无效
			message = "请求VoteID无效,可能指定投票已经截止.";
		}
		request.setAttribute("message", message);
		request.getRequestDispatcher("finished.jsp").forward(request, response);
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
